package com.liuguang.common.validator;

import com.liuguang.common.annotations.IsPhoneNumber;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @ClassName: IsMobileValidator
 * @Description：
 * @Author: wanghr
 * Date: 3:45 PM 2020/9/13
 * Version: 1.0
 */
public class IsMobileValidator implements ConstraintValidator<IsPhoneNumber, String> {

    private boolean require = false;

    private final String PARTEN = "^1[3456789]\\d{9}$";

    @Override
    public void initialize(IsPhoneNumber constraintAnnotation) {
        require = constraintAnnotation.require();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (require) {
            if (StringUtils.isEmpty(value)) return false;
            boolean matches = Pattern.matches(PARTEN, value);
            if (matches) return true;
            return false;
        }
        return true;
    }
}
